﻿using Dapper;
using MiniApiProject.Data;
using MiniApiProject.Models;

namespace MiniApiProject.Services;

public class BookService(IDbConnectionFactory factory) : IBookService
{
	public async Task<bool> DeleteBookAsync(string isbn)
	{
		if (string.IsNullOrEmpty(isbn)) return false;
		var connection = await factory.GetConnection();
		var result = await connection.ExecuteAsync(@"DELETE FROM Books WHERE Isbn=@isbn", new { isbn });
        return result > 0;
	}

	public async Task<Book?> GetBookByIsbnAsync(string isbn)
	{
		var connection = await factory.GetConnection();
		var book = await connection.QueryFirstOrDefaultAsync<Book>(@"SELECT * FROM Books WHERE Isbn=@isbn", new { isbn });
		return book;
	}

	public async Task<IEnumerable<Book>> GetBooksAsync()
	{
		var connection = await factory.GetConnection();
		var books = await connection.QueryAsync<Book>(@"SELECT * FROM Books");
        return books;
	}

	public async Task<IEnumerable<Book>> GetBooksByTitleAsync(string title)
	{
		var connection = await factory.GetConnection();
		var books = await connection.QueryAsync<Book>($"SELECT * FROM Books WHERE Title LIKE '%{title}%'");
		return books;
	}

	public async Task<bool> InsertBookAsync(Book book)
	{
		var connection = await factory.GetConnection();
		var result = await connection.ExecuteAsync("""
                INSERT INTO Books (Title, Author, Isbn, Price, PageCount, PublishDate) 
                VALUES (@Title, @Author, @Isbn, @Price, @PageCount, @PublishDate)
                """, book);
		return result > 0;
	}

	public async Task<bool> UpdateBookAsync(Book book)
	{
		if (string.IsNullOrEmpty(book.Isbn)) return false;
        var connection = await factory.GetConnection();
        var result = await connection.ExecuteAsync("""
                UPDATE Books SET Title=@Title, Author=@Author, Price=@Price, PageCount=@PageCount, PublishDate=@PublishDate, Description=@Description
                WHERE Isbn=@Isbn
                """, book);
		return result > 0;
	}
}
